<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="菜单名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入菜单名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="菜单状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb-10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          @click="handleExpandAll"
        >展开/折叠</el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="menuList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="菜单名称" prop="name" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图标" align="center" width="100">
        <template #default="scope">
          <el-icon v-if="scope.row.icon">
            <component :is="scope.row.icon" />
          </el-icon>
          <span v-else>{{ scope.row.icon }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" width="60" align="center" />
      <el-table-column label="权限标识" prop="perms" :show-overflow-tooltip="true" />
      <el-table-column label="组件路径" prop="component" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'danger' : 'success'">
            {{ scope.row.status === '0' ? '停用' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            @click="handleAdd(scope.row)"
            v-if="scope.row.type !== 'F'"
          >新增</el-button>
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="menuForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="form.parentId"
            :data="menuOptions"
            :props="{ label: 'title', value: 'id', children: 'children' }"
            value-key="id"
            placeholder="选择上级菜单"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="form.type !== 'F'">
          <el-input v-model="form.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="路由地址" prop="path" v-if="form.type !== 'F'">
          <el-input v-model="form.path" placeholder="请输入路由地址" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="form.type === 'C'">
          <el-input v-model="form.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="权限标识" prop="perms" v-if="form.type !== 'M'">
          <el-input v-model="form.perms" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="显示状态" v-if="form.type !== 'F'">
          <el-radio-group v-model="form.hidden">
            <el-radio :label="false">显示</el-radio>
            <el-radio :label="true">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listMenu, getMenu, delMenu, addMenu, updateMenu, treeMenu } from '@/api/system/menu'

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 菜单表格数据
const menuList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 是否展开所有
const isExpandAll = ref(true)
// 重新渲染表格状态
const refreshTable = ref(true)
// 菜单树选项
const menuOptions = ref([])
// 表单参考
const menuForm = ref(null)

// 状态数据字典
const statusOptions = [
  { value: '0', label: '停用' },
  { value: '1', label: '正常' }
]

// 查询参数
const queryParams = reactive({
  title: undefined,
  status: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  parentId: 0,
  name: undefined,
  icon: undefined,
  type: 'M',
  sort: 0,
  path: undefined,
  component: undefined,
  perms: undefined,
  hidden: false,
  status: '1'
})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '菜单名称不能为空', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '路由地址不能为空', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
  ]
}

// 获取菜单列表
const getList = () => {
  loading.value = true
  listMenu(queryParams).then(response => {
    menuList.value = response.data
    loading.value = false
  })
}

// 查询菜单下拉树结构
const getTreeSelect = () => {
  treeMenu().then(response => {
    menuOptions.value = [{ id: 0, title: '主目录', children: response.data }]
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.parentId = 0
  form.title = undefined
  form.icon = undefined
  form.type = 'M'
  form.sort = 0
  form.path = undefined
  form.component = undefined
  form.permission = undefined
  form.hidden = false
  form.status = '1'
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.title = undefined
  queryParams.status = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 展开/折叠操作
const handleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

// 新增按钮操作
const handleAdd = (row) => {
  reset()
  getTreeSelect()
  if (row && row.id) {
    form.parentId = row.id
  }
  open.value = true
  title.value = '添加菜单'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  getTreeSelect()
  const menuId = row.id || ids.value[0]
  getMenu(menuId).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = '修改菜单'
  })
}

// 提交按钮
const submitForm = () => {
  menuForm.value.validate(valid => {
    if (valid) {
      if (form.id !== undefined) {
        updateMenu(form).then(response => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addMenu(form).then(response => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  const menuIds = row.id || ids.value
  ElMessageBox.confirm('是否确认删除菜单编号为"' + menuIds + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return delMenu(menuIds)
  }).then(() => {
    getList()
    ElMessage.success('删除成功')
  })
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}
</style>